package service;

import role.MasterRole;
import role.SlaveRole;


public class ServiceWrapper {
	

	
	@SuppressWarnings("rawtypes")
	public static void main(String[] args) throws Exception {
		//mainLoop(args[0]);
		
		boolean master = false;
		boolean slave = false;
		for(String arg : args) {
			if (arg.equals("master")) {
				master = true;
			}
			if (arg.equals("slave")) {
				slave = true;
			}
		}
		Class serviceClass = Class.forName(args[0]);
		
		AbstractService service = (AbstractService) serviceClass.newInstance();
		
		service.startCommunication();
		
		if (master) {
			service.addRole(new MasterRole());
		}
		if (slave) {
			service.addRole(new SlaveRole());
		}
		
		try {
			service.init();
			service.run();

			while (!service.isClosed()) {
				Thread.sleep(1000);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			service.stopCommunication();			
		}
	}

	public static void mainLoop(String serviceClassName)
			throws ClassNotFoundException, InstantiationException,
			IllegalAccessException, InterruptedException {
		Class serviceClass = Class.forName(serviceClassName);
		
		AbstractService service = (AbstractService) serviceClass.newInstance();
		
		service.startCommunication();
		
		try {
			service.init();
			service.run();

			while (!service.isClosed()) {
				Thread.sleep(1000);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			service.stopCommunication();			
		}
	}

}
